package com.sgcc.electricjournal.controller;

import com.sgcc.electricjournal.entity.PageResult;
import com.sgcc.electricjournal.entity.QueryPageBean;
import com.sgcc.electricjournal.entity.Result;
import com.sgcc.electricjournal.entity.StatusCode;
import com.sgcc.electricjournal.pojo.Journal;
import com.sgcc.electricjournal.pojo.LogContent;
import com.sgcc.electricjournal.pojo.LogDetail;
import com.sgcc.electricjournal.pojo.Login;
import com.sgcc.electricjournal.service.JournalService;
import com.sgcc.electricjournal.util.DateUtil;
import com.sgcc.electricjournal.util.ExportExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


//import javax.ws.rs.GET;

@Controller
/*@RequestMapping("/journal")*/
@CrossOrigin
public class JournalController {

    private Logger log = LoggerFactory.getLogger(JournalController.class);

    public String usernameGloble = "";

    @Autowired
    private JournalService journalService;

    @Value("${downExcelPath}")
    private String downExcelPath;

    @GetMapping("/login")
    public String login() {

        return "login";
        //return "elog";
    }

    @GetMapping("/elog")
    public String elog(HttpServletRequest request) {

        HttpSession session = request.getSession();

        Object username = session.getAttribute("username");

        if (username == null) {
            return "login";
        }
        return "elog";
    }

    /*@PostMapping("/loginHandle")
    public ModelAndView loginHandle(Login login,ModelAndView modelAndView){


        boolean flag = journalService.login(login);

        if(flag){

            modelAndView.addObject("username",login.getUsername());
            modelAndView.setViewName("elog");
            tranTest();

        }else {
            modelAndView.addObject("msg","用户名或密码错误");
            modelAndView.setViewName("login");
        }

        return modelAndView;
    }*/
    @PostMapping("/loginHandle")
    @ResponseBody
    public Result loginHandle(@RequestBody Login login, HttpServletRequest request) {

        boolean flag = true;

        if (StringUtils.isEmpty(login.getUsername())) {
            return new Result(false, StatusCode.ERROR, "用户名不能为空");
        }
        usernameGloble = login.getUsername();
        //flag = journalService.login(login);

        if (flag) {
            // 2.4 如果用户名和密码都正确, 就应该将用户信息保存到session中, 作为用户在线的依据
            // request.getSession(true)     如果内存中有对应的session, 就直接使用; 如果没有对应的session, 创建一个新的返回
            // request.getSession(false)    如果内存中有对应的session, 就直接使用; 如果没有对应的session, 返回null
            request.getSession(true).setAttribute("username", login.getUsername());
            return new Result(true, StatusCode.OK, "登录成功", login);
        } else {
            return new Result(false, StatusCode.ERROR, "用户名错误");
        }


    }


    /**
     * 用户退出
     */
    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 销毁session中的用户信息
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate(); // 销毁session容器, 容器中的数据也销毁了
        }
        return new Result(true, StatusCode.OK, "重新登录");

    }

    /**
     * 获取用户名
     */
    @GetMapping("/getUsername")
    @ResponseBody
    public Result getUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        HttpSession session = request.getSession(false);

        String username = "";
        if (session != null) {
            username = (String)session.getAttribute("username");
        }
        return new Result(true, StatusCode.OK, "重新登录",username);
    }


    @RequestMapping("/detail")
    public String findDetail(ModelAndView modelAndView) {

        modelAndView.addObject("testDate", "123456");

        return "createLog.html";
    }

    /**
     * @param journal
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Journal journal) {
        journal.setId(String.valueOf(UUID.randomUUID()));
        journal.setCreateTime(new Date());

        journalService.add(journal,usernameGloble);

        return new Result(true, StatusCode.OK, "添加成功");
    }

    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping("/findAll")
    @ResponseBody
    public Result findAll() {

        List<Journal> journalList = journalService.findAll();

        return new Result(true, StatusCode.OK, "查询成功", journalList);
    }

    /**
     * 根据id查询日志
     *
     * @param journalId
     * @return
     */
    @GetMapping("/findOneById")
    @ResponseBody
    public Result findOneById(@RequestParam(value = "journalId") String journalId) {

        Journal journal = journalService.findOneById(journalId);

        return new Result(true, StatusCode.OK, "查询成功", journal);
    }

    /**
     * 修改日志
     *
     * @param
     */
    @PostMapping("/update")
    @ResponseBody
    public Result update(@RequestBody Journal journal) {

        //先删除在添加
        journalService.deleteOneById(journal.getId());
        journal.setId(String.valueOf(UUID.randomUUID()));
        journal.setCreateTime(journal.getCreateTime());
        journal.setUpdateTime(new Date());

        List<LogContent> contentList = journal.getContentList();
        for (LogContent logContent : contentList
        ) {
            logContent.setUpdateTime(new Date());
        }

        journalService.add(journal,usernameGloble);

        return new Result(true, StatusCode.OK, "修改成功");
    }


    /**
     * 根据id删除日志
     *
     * @param journalId
     * @return
     */
    @GetMapping("/deleteOneById")
    @ResponseBody
    public Result deleteOneById(@RequestParam(value = "journalId") String journalId) {

        journalService.deleteOneById(journalId);

        return new Result(true, StatusCode.OK, "删除成功");
    }


    /**
     * 分页查询-从昨天凌晨到现在--运行日志
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findByPage")
    @ResponseBody
    public Result findByPage(@RequestBody QueryPageBean queryPageBean) {

        if (StringUtils.isEmpty(queryPageBean.getStartTime())) {
            queryPageBean.setStartTime(DateUtil.addDateHour(DateUtil.toDayStartHour(new Date()), -24));//昨天凌晨
        }
        if (StringUtils.isEmpty(queryPageBean.getEndTime())) {
            queryPageBean.setEndTime(new Date());//当前时间
        }

        PageResult pageResult = journalService.findByPage(queryPageBean);
        return new Result(true, StatusCode.OK, "分页查询成功", pageResult);
    }

    /**
     * 分页查询-从昨天凌晨到现在--查询
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findByPageQuery")
    @ResponseBody
    public Result findByPageQuery(@RequestBody QueryPageBean queryPageBean) {

        if (StringUtils.isEmpty(queryPageBean.getStartTime())) {
            queryPageBean.setStartTime(DateUtil.addDateHour(DateUtil.toDayStartHour(new Date()), -24));//昨天凌晨
        }
        if (StringUtils.isEmpty(queryPageBean.getEndTime())) {
            queryPageBean.setEndTime(new Date());//当前时间
        }

        if ("-1".equals(queryPageBean.getType())) {
            queryPageBean.setType("");
        }
        if ("-1".equals(queryPageBean.getStatus())) {
            queryPageBean.setStatus("");
        }

        PageResult pageResult = journalService.findByPageQuery(queryPageBean);
        return new Result(true, StatusCode.OK, "分页查询成功", pageResult);
    }

    /**
     * 日志运行模块的导出
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/downExcel")
    @ResponseBody
    public boolean downExcel(@RequestBody QueryPageBean queryPageBean,HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(queryPageBean.getStartTime())) {
                queryPageBean.setStartTime(DateUtil.addDateHour(DateUtil.toDayStartHour(new Date()), -24));//昨天凌晨
            }
            if (StringUtils.isEmpty(queryPageBean.getEndTime())) {
                queryPageBean.setEndTime(new Date());//当前时间
            }
            //log.debug("controller{"+queryPageBean+"}");
            List<LogDetail> list = journalService.downExcel(queryPageBean);

            HttpSession session = request.getSession(false);

            //String  username = (String)session.getAttribute("username");

     /*       for (LogDetail log:
            list) {
                log.setRecorder(username);
            }*/

            String title = "电网日志";
            List<String> colNames = Arrays.asList("序号", "日期时间", "厂站", "内容", "状态", "类型", "记录人");
            List<String> attrNames = Arrays.asList("serialNum", "logContentCreateTime", "stationName", "content", "status", "type", "recorder");

            ExportExcelUtil util = new ExportExcelUtil(title, title, colNames.toArray(), attrNames.toArray(), list);
            HSSFWorkbook workbook = util.commonExport();

            //文件写入输出流
            if (workbook != null) {
                String fileName = "电网日志" + DateUtil.format(new Date(), "yyyyMMdd HHmmss") + ".xls";
                File file = new File(downExcelPath + fileName);
                // 如果文件夹不存在则创建
                if (!file.getParentFile().exists() && !file.isDirectory()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                } else {
                    file.createNewFile();
                }

                FileOutputStream out = new FileOutputStream(file);
                workbook.write(out);
                if (out != null) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


        return true;
    }



    /*@RequestMapping("/downExcel")
    @ResponseBody
    public boolean downExcel(@RequestBody QueryPageBean queryPageBean, HttpServletResponse response) {
        try {
            if(StringUtils.isEmpty(queryPageBean.getStartTime())){
                queryPageBean.setStartTime(DateUtil.addDateHour(DateUtil.toDayStartHour(new Date()),-24));//昨天凌晨
            }
            if(StringUtils.isEmpty(queryPageBean.getEndTime())){
                queryPageBean.setEndTime(new Date());//当前时间
            }
            //log.debug("controller{"+queryPageBean+"}");
            List<LogDetail> list = journalService.downExcel(queryPageBean);

            String title = "电网日志";
            List<String> colNames = Arrays.asList("序号","日期时间","厂站","内容","状态","类型","记录人");
            List<String> attrNames = Arrays.asList("serialNum","logContentCreateTime","stationName","content","status","type","recorder");

            ExportExcelUtil util = new ExportExcelUtil(title,title,colNames.toArray(),attrNames.toArray(),list);
            HSSFWorkbook workbook = util.commonExport();

            //文件写入输出流
            if(workbook != null){
                *//*String fileName = "电网日志"+DateUtil.format(new Date(), "yyyyMMdd HHmmss")+".xls";
                File file = new File(downExcelPath+fileName);
                // 如果文件夹不存在则创建
                if (!file.getParentFile().exists()&&!file.isDirectory()){
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                } else {
                    file.createNewFile();
                }

                FileOutputStream out = new FileOutputStream(file);
                workbook.write(out);
                if(out != null){
                    out.close();
                }*//*
//4. 下载excel到本地
                // 通过输出流进行文件下载
                ServletOutputStream out = response.getOutputStream();
                //指定附件的格式为excel
                response.setContentType("application/vnd.ms-excel");
                //attachment 以附件下载
                //下载弹出框架中的默认的文件名
                String fileName = "电网日志"+DateUtil.format(new Date(), "yyyyMMdd HHmmss")+".xls";
                response.setHeader("content-Disposition","attachment;filename="+fileName);
                //输出流下载
                workbook.write(out);
                out.flush();
                out.close();
                workbook.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }


        return true;
    }*/

    /**
     * 查询模块的导出
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/downExcelQuery")
    @ResponseBody
    public boolean downExcelQuery(@RequestBody QueryPageBean queryPageBean) {
        try {
            if (StringUtils.isEmpty(queryPageBean.getStartTime())) {
                queryPageBean.setStartTime(DateUtil.addDateHour(DateUtil.toDayStartHour(new Date()), -24));//昨天凌晨
            }
            if (StringUtils.isEmpty(queryPageBean.getEndTime())) {
                queryPageBean.setEndTime(new Date());//当前时间
            }
            if ("-1".equals(queryPageBean.getType())) {
                queryPageBean.setType("");
            }
            if ("-1".equals(queryPageBean.getStatus())) {
                queryPageBean.setStatus("");
            }
            //log.debug("controller{"+queryPageBean+"}");
            List<LogDetail> list = journalService.downExcelQuery(queryPageBean);

            String title = "电网日志";
            List<String> colNames = Arrays.asList("序号", "日期时间", "厂站", "内容", "状态", "类型", "记录人");
            List<String> attrNames = Arrays.asList("serialNum", "logContentCreateTime", "stationName", "content", "status", "type", "recorder");

            ExportExcelUtil util = new ExportExcelUtil(title, title, colNames.toArray(), attrNames.toArray(), list);
            HSSFWorkbook workbook = util.commonExport();

            //文件写入输出流
            if (workbook != null) {
                String fileName = "电网日志" + DateUtil.format(new Date(), "yyyyMMdd HHmmss") + ".xls";
                File file = new File(downExcelPath + fileName);
                // 如果文件夹不存在则创建
                if (!file.getParentFile().exists() && !file.isDirectory()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                } else {
                    file.createNewFile();
                }

                FileOutputStream out = new FileOutputStream(file);
                workbook.write(out);
                if (out != null) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


        return true;
    }
}
